package com.jia.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jia.product.entity.Category;
import com.jia.product.mapper.CategoryMapper;
import com.jia.product.service.CategoryBrandRelationService;
import com.jia.product.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.jia.product.constants.ProductAttribute.PRODUCT_CATEGORY_PARENT;

/**
 * 商品三级分类(Category)表服务实现类
 *
 * @author makejava
 * @since 2025-07-08 18:15:26
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public List<Category> treeList() {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
//        wrapper.eq("show_status", PRODUCT_SALES_STATUS);
        List<Category> categories
                = this.baseMapper.selectList(wrapper);
        return categories.stream()
                .filter(category -> Objects.equals(category.getParentCid(), PRODUCT_CATEGORY_PARENT))
                .peek(category -> category.setChildren(getChildList(category, categories)))
                .sorted(Comparator.comparingInt(Category::getSort))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateShowStatusListById(List<String> idList) {
        int count = this.baseMapper.updateShowStatusListById(idList);
        if (count <= 0) {
            throw new RuntimeException("下架失败，请检查商品");
        }
        return count;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPaths = findParentPath(catelogId, paths);
        Collections.reverse(parentPaths);
        return parentPaths.toArray(new Long[0]);
    }

    @Override
    public void updateByIdRelation(Category category) {
        updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            // 级联修改
            categoryBrandRelationService.updateDetailByCategory(category);
        }
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        Category category = this.getById(catelogId);
        if (category.getParentCid() != 0) {
            findParentPath(category.getParentCid(), paths);
        }
        return paths;
    }

    private List<Category> getChildList(Category root, List<Category> categorieList) {
        return categorieList.stream()
                .filter(child -> child.getParentCid().equals(root.getCatId()))
                .peek(category -> category.setChildren(getChildList(category, categorieList)))
                .sorted(Comparator.comparingInt(Category::getSort))
                .collect(Collectors.toList());
    }


}

